package com.psy.counseling.controller;


import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.utils.Result;
import com.psy.counseling.entity.Comment;
import com.psy.counseling.service.CommentService;
import com.psy.counseling.service.UserService;
import org.springframework.web.bind.annotation.*;
import com.psy.counseling.entity.User;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;

/**
 * <p>
 *  评论管理的增删改查
 * </p>
 *
 * @author 梁学儒
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;
    @Resource
    HttpServletRequest request;
    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @PostMapping
    public Result<?> save(@RequestBody Comment comment) {
        comment.setUsername(getUser().getUsername());
        comment.setTime(DateUtil.formatDateTime(new Date()));
        return Result.success(commentService.save(comment));
    }

    @PutMapping
    public Result<?> update(@RequestBody Comment comment) {

        return Result.success(commentService.updateById(comment));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        commentService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(commentService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(commentService.list());
    }

    @GetMapping("/foreign")
    public Result<?> findByForeign() {
        return Result.success(commentService.findByForeign());
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Comment> query = Wrappers.<Comment>lambdaQuery().like(Comment::getContent, name).orderByDesc(Comment::getId);
        return Result.success(commentService.page(new Page<>(pageNum, pageSize), query));
    }


}

